#!/usr/bin/env python
#-*- coding:utf-8 -*-
from flask import render_template, request, redirect, url_for, send_from_directory, Response, jsonify
from . import main
from forms import DailyForm
from ..models import Daily
from .. import db
from flask_login import login_required, current_user
from datetime import datetime, timedelta, date
import xlsxwriter, time, os, sys
from ..config import Config
import sys, json
reload(sys)
sys.setdefaultencoding('utf-8')


@main.route('/')
@login_required
def index():
    if (datetime.now()).strftime( '%a' ) == 'Mon':
        yestoday = datetime.now() - timedelta(days=3)
    else:
        yestoday = datetime.now() - timedelta(days=1)

    if current_user.role.name == 'Administrators':
        page_index = request.args.get('page', 1, type=int)
        query=Daily.query.filter(Daily.update_time.between(yestoday, datetime.now())).order_by(
        Daily.update_time.desc())
        pagination = query.paginate(page_index, per_page=20, error_out=False)
        dailys = pagination.items
        return render_template('index.html',
                           title=u"日报记录",
                           dailys=dailys,
                            pagination=pagination)
    else:
        dailys = Daily.query.filter((Daily.author == current_user),(Daily.update_time.between(yestoday,datetime.now()))).order_by(Daily.update_time.desc())
        return render_template('index.html',
                                title=u"日报记录",
                                dailys=dailys)


@main.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404




@main.route('/about')
def about():
    return render_template('about.html',title=u'关于')


@main.route('/new', methods=['GET', 'POST'])
@login_required
def new():
    title = u'添加日报'
    if request.method == 'POST':
        add_num = (len(request.form) / 4)
        for i in range(1,add_num + 1):
            daily = Daily(author=current_user)
            item = "daily[%s].item" %i
            detail = "daily[%s].detail" %i
            status = "daily[%s].status" %i
            finsh_time = "daily[%s].finshtime" %i
            daily.item = request.form[item]
            daily.detail = request.form[detail]
            daily.status = request.form[status]
            daily.finsh_time = request.form[finsh_time]
            print (daily.item, daily.detail,daily.status, daily.finsh_time)
        db.session.add(daily)
        db.session.commit()
        return redirect(url_for('.index'))
    return render_template('new.html', title=title)


@main.route('/export', methods=['GET', 'POST'])
@login_required
def export():
    exportDir = os.getcwd() + Config.EXPORT_FOLDER
    currHour = time.strftime('%Y%m%d', time.localtime())
    filename = 'daily_%s_%s.xlsx' % (current_user.realname, currHour)
    exportFile = os.path.join(exportDir, filename)
    if not os.path.exists(exportDir):
        os.makedirs(exportDir)

    today = datetime(datetime.now().year, datetime.now().month, datetime.now().day, 0, 0, 0, 0)
    if current_user.role.name == "Administrators":
        daily_data = Daily.query.filter(Daily.update_time.between(today, datetime.now())).group_by(Daily.author_id, Daily.item).all()
    else:
        daily_data = Daily.query.filter((Daily.author == current_user),
                                (Daily.update_time.between(today, datetime.now()))).order_by(Daily.item)
    workbook = xlsxwriter.Workbook(exportFile)
    worksheet = workbook.add_worksheet(currHour)
    title = [u'部门', u'事项',u'事项详情', u'状态', u'责任人', u'计划完成时间', u'备注事项']
    bold = workbook.add_format({'bold': True})
    #workbook.add_format({'border': 1, 'align': 'center', 'bg_color': 'cccccc', 'font_size': 13, 'bold': True})
    bold1 = workbook.add_format({'bg_color': '92CDDC','bold': True})
    worksheet.set_column('B:C', 50)
    worksheet.set_column('F:G', 20)
    worksheet.write_row('A1', title, bold1)
    try:
        sum = 1
        for daily in daily_data:
            sum = 1 + sum
            data_column = 'A' + str(sum)
            worksheet.write_row(data_column, ('',daily.item, daily.detail, daily.status, daily.author.realname, daily.finsh_time, daily.desc))
    except Exception as error:
        return error
    finally:
        workbook.close()
    return send_from_directory(exportDir, filename, as_attachment=True)


@main.route('/daily/<int:id>', methods=['GET', 'POST'])
@login_required
def daily(id):
    daily = Daily.query.get_or_404(id)
    form = DailyForm()
    title = u'编辑 -%s' % (daily.item)
    if request.method == 'POST':
        if form.validate_on_submit():

            daily.item = form.item.data
            daily.detail = form.detail.data
            daily.status = form.status.data
            daily.finsh_time = form.finsh_time.data
            db.session.add(daily)
            db.session.commit()
            return redirect(url_for('.index'))
    return render_template('edit.html',
                           title=title,
                           form=form,daily=daily)


@main.route('/delete/<int:id>', methods=['DELETE'])
@login_required
def delete(id):
    try:
         data = Daily.query.filter_by(id=id).first()
         db.session.delete(data)
         db.session.commit()
         msg = "success"
    except:
         msg = "not delete"
    msg = "success"
    return jsonify({"msg": msg}), 201

